import Foundation

// 简单的API测试程序
func testOpenAIConnection() {
    print("开始测试OpenAI API连接...")
    
    // 准备API请求
    guard let url = URL(string: "https://api.openai.com/v1/chat/completions") else {
        print("错误: 无效的URL")
        return
    }
    
    // 使用环境中的API密钥
    let apiKey = "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"
    
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
    
    // 准备请求体
    let requestBody: [String: Any] = [
        "model": "gpt-4o",
        "messages": [
            ["role": "user", "content": "你好，这是一个API测试。请用一句话回复我。"]
        ],
        "stream": true,
        "temperature": 0.7
    ]
    
    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: requestBody)
    } catch {
        print("错误: 无法序列化请求体 - \(error)")
        return
    }
    
    // 创建会话和数据任务
    let session = URLSession.shared
    let task = session.dataTask(with: request) { data, response, error in
        if let error = error {
            print("连接错误: \(error)")
            return
        }
        
        guard let httpResponse = response as? HTTPURLResponse else {
            print("错误: 无效的HTTP响应")
            return
        }
        
        print("HTTP状态码: \(httpResponse.statusCode)")
        
        guard (200...299).contains(httpResponse.statusCode) else {
            if let data = data, let errorText = String(data: data, encoding: .utf8) {
                print("HTTP错误 \(httpResponse.statusCode): \(errorText)")
            } else {
                print("HTTP错误 \(httpResponse.statusCode)")
            }
            return
        }
        
        guard let data = data else {
            print("错误: 没有数据返回")
            return
        }
        
        // 如果是流式返回，解析SSE格式数据
        if let text = String(data: data, encoding: .utf8) {
            print("接收到数据:\n\(text)")
            
            let lines = text.components(separatedBy: "\n")
            var fullResponse = ""
            
            for line in lines {
                if line.hasPrefix("data: ") {
                    let jsonString = line.dropFirst(6) // 去掉 "data: "
                    
                    if jsonString == "[DONE]" {
                        print("流结束")
                        continue
                    }
                    
                    do {
                        if let data = String(jsonString).data(using: .utf8),
                           let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                           let choices = json["choices"] as? [[String: Any]],
                           let choice = choices.first,
                           let delta = choice["delta"] as? [String: Any],
                           let content = delta["content"] as? String {
                            fullResponse += content
                            print("收到流式内容片段: \(content)")
                        }
                    } catch {
                        print("解析JSON错误: \(error)")
                    }
                }
            }
            
            print("完整响应: \(fullResponse)")
        } else {
            print("错误: 无法将数据解码为字符串")
        }
    }
    
    task.resume()
    
    // 保持主线程运行一段时间以等待异步完成
    RunLoop.main.run(until: Date(timeIntervalSinceNow: 15))
}

// 运行测试
print("开始API测试...")
testOpenAIConnection()
print("测试结束") 